package com.gxz.logbacktest.controller;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping(value = {"/log"})
public class TestLogController {

    private static final Logger logger = LogManager.getLogger(TestLogController.class);
    private String infoMsg = RandomUtil.randomString(1024 * 64);

    @GetMapping(value = "/justLog")
    public String justLog() {
        logger.info("infoMsg");
        return "成功返回！";
    }

    @GetMapping(value = "/getid")
    public String getid() {
        long datacenterId = getDatacenterId(31L);

        long workerId = getMaxWorkerId(getDatacenterId(31L), 31L);
        String msg = StrUtil.format("datacenterId：{},workerId:{}", datacenterId, workerId);
        log.info(msg);
        return msg;
    }

    protected long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            log.info("name:{}", name);
            mpid.append(name.split("@")[0]);
        }

        return (long) (mpid.toString().hashCode() & '\uffff') % (maxWorkerId + 1L);
    }

    protected long getDatacenterId(long maxDatacenterId) {
        long id = 0L;

        try {
            NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            if (null == network) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    log.info("mac:{}", Arrays.toString(mac));
                    id = (255L & (long) mac[mac.length - 2] | 65280L & (long) mac[mac.length - 1] << 8) >> 6;
                    id %= maxDatacenterId + 1L;
                }
            }
        } catch (Exception var7) {
            Exception e = var7;
            logger.warn(" getDatacenterId: " + e.getMessage());
        }

        return id;
    }
}
